package cn.pconline.autoclub.service;

import cn.pconline.autoclub.entity.AppBanner;
import cn.pconline.autoclub.entity.Club;
import java.util.Collections;
import java.util.List;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;

/**
 *
 * @author <a href="mailto:chensy0203@163.com">chensy</a>
 */
public class AppBannerService {

    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private GeliDao geliDao;
    @Autowired
    private ClubService clubService;
    private static final Logger log = LoggerFactory.getLogger(AppBannerService.class);

    /**
     * 获取所有banner
     *
     * @return
     */
    public List<AppBanner> getAllList() {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select banner_id from ").appendSql(geliOrm.getTableName(AppBanner.class));
        try {
            return geliDao.list(AppBanner.class, sql.getSql());
        } catch (EmptyResultDataAccessException e) {
            return Collections.EMPTY_LIST;
        }
    }

    /**
     * 查找某一Banner
     *
     * @param bannerId
     * @return
     */
    public AppBanner findById(long bannerId) {
        try {
            return geliDao.find(AppBanner.class, bannerId);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    /**
     * 给车友会设置banner
     *
     * @param clubId
     * @param bannerId
     * @return
     */
    public boolean setAppBanner(long clubId, long bannerId) {
        Club club = clubService.getClub(clubId);
        if (club == null) {
            log.error("club[{}] 不存在！", clubId);
            return false;
        }
        AppBanner banner = findById(bannerId);
        if (banner == null) {
            log.error("banner[{}] 不存在！", bannerId);
            return false;
        }
        club.setAppBanner(banner.getUrl());
        club.setBannerId(bannerId);
        return geliDao.update(club, "banner_id,app_banner") > 0;
    }
}
